package com.sujeet.learning.soap;

import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Vector;

import org.apache.soap.Constants;
import org.apache.soap.Fault;
import org.apache.soap.SOAPException;
import org.apache.soap.rpc.Call;
import org.apache.soap.rpc.Parameter;
import org.apache.soap.rpc.Response;
import org.apache.soap.encoding.SOAPMappingRegistry;
import org.apache.soap.encoding.soapenc.BeanSerializer;
import org.apache.soap.util.xml.QName;

public class CDLister {
	@SuppressWarnings("rawtypes")
	public void list(URL url) throws SOAPException {
		System.out.println("Listing current CD catalog.");
		// Map this type so SOAP can use it
		SOAPMappingRegistry registry = new SOAPMappingRegistry( );
		BeanSerializer serializer = new BeanSerializer( );
		registry.mapTypes(Constants.NS_URI_SOAP_ENC,
				new QName("urn:cd-catalog-demo", "cd"),
				CD.class, serializer, serializer);
		// Build the Call object
		Call call = new Call();
		call.setSOAPMappingRegistry(registry);
		call.setTargetObjectURI("urn:cd-catalog");
		call.setMethodName("list");
		call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
		// No parameters needed
		// Invoke the call
		Response response;
		response = call.invoke(url, "");
		if (!response.generatedFault()) {
			Parameter returnValue = response.getReturnValue();
			Hashtable catalog = (Hashtable) returnValue.getValue();
			Enumeration e = catalog.keys();
			while (e.hasMoreElements()) {
				String title = (String) e.nextElement();
				CD cd = (CD) catalog.get(title);
				System.out.println(cd);
			}
		} else {
			Fault fault = response.getFault();
			System.out.println("Error encountered: " + fault.getFaultString());
			Vector entries = fault.getDetailEntries( );
			for (Iterator i = entries.iterator(); i.hasNext( ); ) {
			org.w3c.dom.Element entry = (org.w3c.dom.Element)i.next( );
			System.out.println(entry.getFirstChild().getNodeValue( ));
			}

		}
	}

	public static void main(String[] args) {
		
		System.out.println("Provide URL. e.g. http://localhost:6464/soap/servlet/rpcrouter\n");
		Scanner scanner = new Scanner(System.in);
		// http://localhost:6464/soap/servlet/rpcrouter
		// http://localhost:80/soap/servlet/rpcrouter
		String urlStr = scanner.nextLine();

		try {
			// URL for SOAP server to connect to
			// URL url = new URL("http://localhost:80/soap/servlet/rpcrouter");
			URL url = new URL(urlStr);
			// List the current CDs
			CDLister lister = new CDLister();
			lister.list(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
